package com.wut.clock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.wut.clock.common.exception.Asserts;
import com.wut.clock.entity.Tag;
import com.wut.clock.mapper.ArticleTagMapper;
import com.wut.clock.mapper.TagMapper;
import com.wut.clock.service.ITagService;
import com.wut.clock.vo.admin.TagVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: yuwei
 * @Date: 2022/6/1 11:19
 * @Description:
 */

@Service
@RequiredArgsConstructor
public class TagServiceImpl implements ITagService {

    private final TagMapper tagMapper;

    private final ArticleTagMapper articleTagMapper;

    @Override
    public void saveTag(Tag tag) {
        //查询标签名重复
        Tag existTag = tagMapper.selectOne(new LambdaQueryWrapper<Tag>()
                .eq(Tag::getTagName, tag.getTagName()));
        if (Objects.nonNull(existTag)) {
            Asserts.fail("添加失败，标签名已存在");
        }
        tagMapper.insert(tag);
    }

    @Override
    public void deleteTag(Integer tagId) {
        Integer count = articleTagMapper.selectArticleCountByTagId(tagId);
        if (count > 0) {
            Asserts.fail("删除失败，该标签下存在" + count + "篇文章");
        }
        tagMapper.deleteById(tagId);
    }

    @Override
    public void updateTag(Tag tag) {
        //查询标签名重复
        Tag existTag = tagMapper.selectOne(new LambdaQueryWrapper<Tag>()
                .eq(Tag::getTagName, tag.getTagName())
                .ne(Tag::getId,tag.getId()));
        if (Objects.nonNull(existTag)) {
            Asserts.fail("修改失败，该标签名已存在");
        }
        tagMapper.updateById(tag);
    }

    @Override
    public List<TagVo> listTags(Integer pageNum, Integer pageSize, String tagName) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<Tag> tagWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(tagName)) {
            tagWrapper.like(Tag::getTagName,tagName);
        }
        List<Tag> tagList = tagMapper.selectList(tagWrapper);
        List<TagVo> tagVos = new ArrayList<>();
        for (Tag tag : tagList) {
            TagVo tagVo = new TagVo();
            BeanUtils.copyProperties(tag,tagVo);
            Integer articleCount = articleTagMapper.selectArticleCountByTagId(tag.getId());
            tagVo.setArticleCount(articleCount);
            tagVos.add(tagVo);
        }
        return tagVos;
    }

    @Override
    public List<Tag> listTagsForSelect() {
        return tagMapper.selectList(null);
    }
}
